package DynamicArray;

import java.util.function.Consumer;

public class DynamicArrayInsert {
  private int size = 0; // 逻辑大小
  private int capacity = 8; // 容量
  private int array[] = {};

  public void addLast(int element) {
    checkandGrow();

    array[size] = element;
    size++;
  }

  //  在指定位置添加元素
  public void add(int index, int element) {
    checkandGrow();

    System.arraycopy(array, index, array, index + 1, size - index);
    array[index] = element;
    size++;
  }

  // 容量检查与扩容
  private void checkandGrow() {
    // 懒惰初始化
    if (size == 0) {
      array = new int[capacity];
    } else if (size == capacity) {
      capacity += capacity >>> 1;
      int newArray[] = new int[capacity];
      System.arraycopy(array, 0, newArray, 0, size);
      array = newArray;
    }
  }

  // 遍历方法
  public void forEach(Consumer<Integer> consumer) {
    for (int i = 0; i < size; i++) {
      consumer.accept(array[i]);
    }
  }

  // 删除方法
  public int remove(int index) {
    int removeItem = array[index];
    if (index < size - 1) {
      System.arraycopy(array, index + 1, array, index, size - index - 1);
    }
    size--;
    return removeItem;
  }
}
